package com.woniuxy.financeassembly.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniuxy.api.OrderApi;
import com.woniuxy.common.PageResult;
import com.woniuxy.common.Result;
import com.woniuxy.financeassembly.model.PlatformRecords;
import com.woniuxy.financeassembly.dao.PlatformRecordsMapper;
import com.woniuxy.financeassembly.service.IFinancialManagementBillService;
import com.woniuxy.financeassembly.service.IPlatformRecordsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.form.OrderForm;
import com.woniuxy.form.OrderTransferForm;
import com.woniuxy.hotel.form.HotelBillForm;
import com.woniuxy.hotel.form.IncomeAccountForm;
import com.woniuxy.hotel.form.PlatformRecordsForm;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;


import javax.annotation.Resource;
import java.sql.Timestamp;
import java.text.DateFormat;


import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zz
 * @since 2021-05-24
 */
@Service
@Slf4j
public class PlatformRecordsServiceImpl extends ServiceImpl<PlatformRecordsMapper, PlatformRecords> implements IPlatformRecordsService {

    @Autowired
    private PlatformRecordsMapper platformRecordsMapper;

    @Autowired
    private IFinancialManagementBillService billService;

    @Resource
    private OrderApi orderApi;

    //随机生成订单号的方法
    public static String getOrderIdByTime() {
        SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
        String newDate=sdf.format(new Date());
        String result="";
        Random random=new Random();
        for(int i=0;i<3;i++){
            result+=random.nextInt(10);
        }
        return newDate+result;
    }

    public List<PlatformRecords> account(Integer status, String time){
        Timestamp time1 = null;
        try {
            time1 =new Timestamp(new SimpleDateFormat("yyyy:MM:dd").parse(time).getTime());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        log.info("time1{}",time1);
        QueryWrapper<PlatformRecords> wrapper = new QueryWrapper<>();
        wrapper.eq("status",status);
        wrapper.eq("record_time",time1);
        List<PlatformRecords> platformRecords = platformRecordsMapper.selectList(wrapper);
        return platformRecords;

    }



    //生成收入流水
    public void addIncomeAccount(IncomeAccountForm incomeAccountForm) {
        log.info("incomeAccountForm{}",incomeAccountForm);

        PlatformRecords platformRecords = new PlatformRecords();
        BeanUtils.copyProperties(incomeAccountForm,platformRecords);
        platformRecords.setStatus(0);//收入时 默认为0

        platformRecordsMapper.insert(platformRecords);

    }

    @GlobalTransactional//分布式事务的方法加上注解
    // 生成支出流水（给商家打账）
    public void addDisburseAccount() {
        //订单已完成状态的所有订单id和金额
        List<OrderTransferForm> orders = orderApi.findOrderByStatus();
        log.info("订单已完成状态的所有订单{}",orders);
        //遍历已完成的订单
        for(OrderTransferForm order : orders) {
            System.out.println(order);

            //打账同时商家要生成账单
            HotelBillForm hotelBillForm = new HotelBillForm();
            //表示平台收到的用户下单金额
            Double actualAmount = order.getActualAmount();
            //表示平台抽1成后 转给商家
            double billMonry = actualAmount * 0.9;
            hotelBillForm.setBillMoney(billMonry);
            hotelBillForm.setHotelId(order.getHotelId());
            hotelBillForm.setBillStatus(1);//状态为1时 表示已结算
            String orderIdByTime = getOrderIdByTime();//随机生成账单号
            log.info("随机生成的账单号{}",orderIdByTime);
            hotelBillForm.setBillNumber(orderIdByTime);
            //生成商家账单
            billService.addHotelBill(hotelBillForm);

            log.info("生成的商家订单{}",hotelBillForm);

            //订单完成时打账（生成平台支出流水）
            PlatformRecords platformRecords = new PlatformRecords();
            platformRecords.setStatus(1);//status为1时 表示支出
            platformRecords.setBillNumber(orderIdByTime);//支出的订单号 也是关联商家账单号
            platformRecords.setFundsOutput("转账");//支出的名字
            platformRecords.setFundsAmount(billMonry);//涉及金额

            platformRecordsMapper.insert(platformRecords);
            log.info("生成的平台流水{}",platformRecords);

            //打账后 要将订单的状态改为已结算,状态为5
            orderApi.modifyOrderStatus(5,order.getOrderId());

        }


        //未完成
    }



//    //平台流水（查询所有收入流水 status为0时）
//    //平台流水（查询所有支出流水 status为1时）
//    public PageResult<PlatformRecordsForm> account(@RequestParam(defaultValue = "1")Integer pageIdx , Integer status) {
////        log.info("前端传入的status是：{}",status);
////        List<PlatformRecords> accounts = financialManagementBillMapper.AllAccount(status);
//        PlatformRecords platformRecords = new PlatformRecords();
//        //按照同名字段拷贝数据
//        BeanUtils.copyProperties(PlatformRecordsForm,platformRecords);
//        QueryWrapper wrapper = new QueryWrapper<>();
//        wrapper.like("status",status);
//        //当前页码，每页条数
//        IPage<PlatformRecords> pageParam = new Page(pageIdx,10L);
//        IPage<PlatformRecords> pageResult = platformRecordsMapper.selectPage(pageParam,wrapper);
//
//        //  将mybatis-plus的结果转为我自定义的PageResult
//        PageResult<PlatformRecords> myPageResult =new PageResult<PlatformRecords>((int)pageResult.getTotal(),(int)pageResult.getCurrent(),(int)pageResult.getSize(),pageResult.getRecords());
//        myPageResult.setSuccess(true);
//        return myPageResult;
//    }
//
//
//
//    //生成收入流水
//    public Result addIncomeAccount(PlatformRecordsForm platformRecordsForm) {
//        return null;
//    }
//
//    //生成支出流水（给商家打账）
//    public Result addDisburseAccount(PlatformRecordsForm platformRecordsForm) {
//        return null;
//    }


}
